﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.employee;
using BenCaoXuan.Infrastructure.Dto.PC;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Redis;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.PC;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceStack;
using ServiceStack.Script;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZstdSharp.Unsafe;

namespace BenCaoXuan.Service.Instance.PC
{
    [Inject_]
    public class Sys_Service : Base_Service, I_Sys_Service
    {
        private readonly Customer_IOC _customer_IOC;
        private readonly Product_IOC _product_IOC;
        private readonly Sys_IOC _sys_IOC;
        private readonly Arrange_IOC _arrange_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Appointment_IOC _appointment_IOC;
        private readonly Order_IOC _order_IOC;

        public Sys_Service(Customer_IOC customer_IOC, Product_IOC product_IOC, Sys_IOC sys_IOC, Arrange_IOC arrange_IOC, Login_IOC login_IOC, Appointment_IOC appointment_IOC, Order_IOC order_IOC)
        {
            _customer_IOC = customer_IOC;
            _product_IOC = product_IOC;
            _sys_IOC = sys_IOC;
            _arrange_IOC = arrange_IOC;
            _login_IOC = login_IOC;
            _appointment_IOC = appointment_IOC;
            _order_IOC = order_IOC;
        }

        /// <summary>
        /// 获取客户(搜索)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> GetCustoms(Customs_Dto dto)
        {
            var data = await _customer_IOC._customer_EFCore.GetAll(out int total, dto.page, dto.limit, false, d => d.CCreateTime, d => d.CPhone.Contains(dto.key)).Select(d => new Customs_Dto
            {
                name = d.CName,
                id = d.CId,
                phone = d.CPhone,
            }).ToListAsync();

            return Get_Result(1, "ok", new
            {
                total = total,
                data = data
            });
        }

        /// <summary>
        /// 获取预约商品(搜索)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Appointment_Product(Product_Dto dto)
        {
            var now = DateTime.Now;

            // 先全局搜索产品和套餐信息
            var allProducts = await _product_IOC._product_EFCore.GetAll(false, d => d.PName.Contains(dto.key), d => d.PIsBan != 1)
                .Select(d => new Product_Dto
                {
                    name = d.PName,
                    id = d.PId,
                    type = d.PTypeId,
                    productattention = d.PProductAttention,
                    Isgroup = d.PIsGroup,
                    photo=d.PCover,
                }).ToListAsync();

            var allPackages = await _product_IOC._productPackage_EFCore.GetAll(false, d => d.PpName.Contains(dto.key), d => d.PpIsBan != 1 && d.PpStartTime <= now && d.PpEndTime >= now)
                .Select(d => new Product_Package_Dto
                {
                    id = d.PpId,
                    name = d.PpName,
                    original_price = d.PpOriginalPrice,
                    price = d.PpPrice,
                    Isban = d.PpIsBan,
                    start_time = d.PpStartTime,
                    end_time = d.PpEndTime,
                    CreateTime = d.PpCreateTime,
                    UpdateTime = d.PpUpdateTime,
                    description = d.PpDescription,
                    remark = d.PpRemark,
                    photo=d.PpPhoto,
                }).ToListAsync();

            // 获取产品规格信息
            var specs = await _product_IOC._productSpecs_EFCore.GetAll(d => d.PsIsBan != 1)
                .Select(d => new Product_Specs_Dto
                {
                    name = d.PsName,
                    p_sid = d.PsId, // 规格id
                    p_id = d.PsProductId, // 产品id
                    price = d.PsPrice,
                    remark = d.PsRemark,
                }).ToListAsync();

            // 获取套餐详情信息
            var packageDetails = await _product_IOC._productPackageDetails_EFCore.GetAll()
                .Select(d => new Product_Package_Details_Dto
                {
                    id = d.PpdId,
                    p_pid = d.PpdPackageId, // 套餐id
                    p_id = d.PpdProductId, // 产品id
                    p_sid = d.PpdProductSpecsId, // 规格id
                    s_name = d.PpdProductSpecsName, // 规格名称
                    sort = d.PpdSort,
                    CreateTime = d.PpdCreateTime,
                    remark = d.PpdRemark,
                }).ToListAsync();

            // 分页处理产品信息
            var pagedProducts = allProducts.Skip((dto.page - 1) * dto.limit).Take(dto.limit).ToList();
            var pagedPackages = allPackages.Skip((dto.page - 1) * dto.limit).Take(dto.limit).ToList();

            // 组合数据
            var result = new List<dynamic>();

            // 处理分页后的产品信息
            foreach (var product in pagedProducts)
            {
                var productSpecs = specs.Where(s => s.p_id == product.id).Select(s => new
                {
                    id = s.p_sid, // 添加产品规格id
                    specsName = s.name,
                    price = s.price
                }).ToList();

                result.Add(new
                {
                    name = product.name,
                    photo=product.photo,
                    attention = product.productattention,
                    specs = productSpecs
                });
            }

            // 处理分页后的套餐信息
            foreach (var pkg in pagedPackages)
            {
                var packageDetailsForPkg = packageDetails.Where(pd => pd.p_pid == pkg.id).ToList();
                var packageDetailsInfo = packageDetailsForPkg.Select(pd => new
                {
                    detailName = allProducts.FirstOrDefault(p => p.id == pd.p_id)?.name,
                    specsName = pd.s_name
                }).ToList();

                result.Add(new
                {
                    id = pkg.id, // 添加套餐id
                    name = pkg.name,
                    price = pkg.price,
                    photo=pkg.photo,
                    originalPrice = pkg.original_price,
                    details = packageDetailsInfo
                });
            }

            return Get_Result(1, "ok", result);
        }

        /// <summary>
        /// 获取选中日期排班
        /// </summary>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Arrange(string begin, string end)
        {
            // 将字符串转换为 DateTime
            DateTime beginDate = Convert.ToDateTime(begin);
            DateTime endDate = Convert.ToDateTime(end);

            // 获取排班表
            var data = await _arrange_IOC._arrange_EFCore.GetAll()
                .Select(d => new
                {
                    d.ATimeRange, // 班次
                    d.AEid,       // 员工ID，逗号隔开
                    d.ADate       // 日期字符串
                }).ToListAsync();

            // 过滤日期范围
            var filteredData = data
                .Where(d => Convert.ToDateTime(d.ADate) >= beginDate && Convert.ToDateTime(d.ADate) <= endDate)
                .ToList();

            // 获取所有前台员工ID和姓名
            var q_id = await _login_IOC._sysEmployee_EFCore.GetAll(d => d.EPostId == "04091b06026d0002f34de68e7f180449")
                .Select(d => new
                {
                    d.EId,
                    d.EName,
                }).ToListAsync();

            // 将员工ID和姓名映射为字典
            var employeeMap = q_id.ToDictionary(e => e.EId, e => e.EName);

            // 按班次分组
            var groupedByTimeSlot = filteredData
                .GroupBy(d => d.ATimeRange)
                .OrderBy(group => group.Key) // 按班次时间排序
                .Select(group => new
                {
                    TimeSlot = group.Key,
                    DailyAssignments = group
                        .OrderBy(d => Convert.ToDateTime(d.ADate)) // 按日期排序
                        .SelectMany(d => d.AEid.Split(',').Select(eid => employeeMap.ContainsKey(eid) ? employeeMap[eid] : null))
                        .Select(name => new { name })
                        .ToList()
                }).ToList();

            // 确保每个班次的日期都有对应的 null 值
            var dateRange = Enumerable.Range(0, (endDate - beginDate).Days + 1)
                .Select(offset => beginDate.AddDays(offset).ToString("yyyy-MM-dd"))
                .ToList();

            var finalResult = groupedByTimeSlot.Select(group =>
            {
                var assignments = dateRange.Select(date =>
                {
                    var assignment = group.DailyAssignments.FirstOrDefault(a =>
                        filteredData.Any(fd => fd.ADate == date && fd.ATimeRange == group.TimeSlot && fd.AEid.Split(',').Any(eid => employeeMap.ContainsKey(eid) && employeeMap[eid] == a.name)));
                    return assignment ?? new { name = (string)null };
                }).ToList();

                return new
                {
                    TimeSlot = group.TimeSlot,
                    DailyAssignments = assignments
                };
            }).ToList();

            // 返回结果
            return Get_Result(1, "ok", finalResult);
        }

        /// <summary>
        /// 获取客户页面(搜索)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_All_Customs(Customs_Dto dto)
        {
            var data = await _customer_IOC._customer_EFCore.GetAll(out int total, dto.page, dto.limit, false, d => d.CCreateTime, d => d.CPhone.Contains(dto.key)).Select(d => new Customs_Dto
            {
                name = d.CName,
                id = d.CId,
                resource = d.CResource,
                phone = d.CPhone,
                IsConvert = d.CIsConvert,
                CreateTime = d.CCreateTime,
                UpdateTime = d.CUpdateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"),
                remark = d.CRemark,
                point = null,
                vip_begin = null,
                vip_status = null,
            }).ToListAsync();


            data.ForEach(d =>
            {
                var vip = _customer_IOC._customerVip_EFCore.GetAll(c => c.CvCustomerId == d.id);

                if (vip.Any())
                {
                    d.point = vip.Single().CvPoint.ToString();
                    d.vip_begin = vip.Single().CvGetTime.Value.ToString("yyyy-MM-dd hh:mm:ss");
                    d.vip_status = vip.Single().CvStatus;
                }

                var source = _sys_IOC._sysDictionary_EFCore.GetAll(c => c.DId == d.resource).Single();
                d.resource = source.DName;
            });

            return Get_Result(1, "ok", new
            {
                total = total,
                data = data
            });
        }

        /// <summary>
        /// 数据报表
        /// </summary>
        /// <param name="section"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        //public async Task<Api_Result_Dto> Get_Report(string section)
        //{
        //    var appointment_count = 0;
        //    decimal? order_money = 0;
        //    var order_count = 0;
        //    var customs = 0;
        //    List<string> xData = new List<string>();
        //    List<int> orderData = new List<int>();
        //    List<decimal?> incomeData = new List<decimal?>();
        //    var cake = new List<dynamic>();
        //    var customs_order_row = new List<dynamic>(); // 声明一个容器存储客户消费排行的数据
        //    List<int> appointment_interval_count = new List<int>();

        //    if (section == "当天")
        //    {
        //        var now = DateTime.Now.Date;
        //        // 预约总数
        //        appointment_count = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod == now).CountAsync();
        //        // 总营业额
        //        order_money = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1) && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //        // 总订单数
        //        order_count = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1)).CountAsync();
        //        // 总客户量
        //        var appointment_ids = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod == now).Select(d => d.ACustomerId).ToListAsync();
        //        var order_id = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1)).Select(d => d.OCustomerId).ToListAsync();
        //        customs = appointment_ids.Union(order_id).Count();

        //        // 订单与收入数据
        //        for (int i = 0; i < 12; i++)
        //        {
        //            var start = now.AddHours(i * 2);
        //            var end = start.AddHours(2);

        //            // 时间段描述
        //            string timeDescription;
        //            if (i == 11) // 最后一个时间段
        //            {
        //                timeDescription = "22时-24时";
        //            }
        //            else
        //            {
        //                timeDescription = $"{start.Hour}时-{end.Hour}时";
        //            }
        //            xData.Add(timeDescription);

        //            // 每个时间段的订单数量
        //            var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < end).CountAsync();
        //            orderData.Add(orders);

        //            // 每个时间段的总金额
        //            var totalAmount = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < end && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //            incomeData.Add(totalAmount);
        //        }

        //        // 获取订单详情
        //        var order_ids = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1)).Select(d => d.OId).ToListAsync();
        //        var order_details = await _order_IOC._ordersDetails_EFCore.GetAll(d => order_ids.Contains(d.OdOrderId)).Select(d => new
        //        {
        //            d.OdOrderId,
        //            d.OdPackageId, // 套餐id 逗号隔开
        //            d.OdProductId // 产品规格id 逗号隔开
        //        }).ToListAsync();

        //        // 获取套餐表
        //        var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
        //        {
        //            d.PpId,
        //            d.PpName,
        //        }).ToListAsync();

        //        // 获取产品表
        //        var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
        //        {
        //            d.PId,
        //            d.PName,
        //        }).ToListAsync();

        //        // 获取产品规格表
        //        var product_span = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
        //        {
        //            d.PsProductId, // 对应产品表的产品id
        //            d.PsId // 产品规格id
        //        }).ToListAsync();

        //        // 计算套餐和产品的数量
        //        var packageCounts = new Dictionary<string, int>();
        //        var productCounts = new Dictionary<string, int>();

        //        foreach (var detail in order_details)
        //        {
        //            if (!string.IsNullOrEmpty(detail.OdPackageId))
        //            {
        //                var packageIds = detail.OdPackageId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var packageId in packageIds)
        //                {
        //                    if (packageCounts.ContainsKey(packageId))
        //                    {
        //                        packageCounts[packageId]++;
        //                    }
        //                    else
        //                    {
        //                        packageCounts[packageId] = 1;
        //                    }
        //                }
        //            }

        //            if (!string.IsNullOrEmpty(detail.OdProductId))
        //            {
        //                var productSpecIds = detail.OdProductId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var productSpecId in productSpecIds)
        //                {
        //                    var productId = product_span.FirstOrDefault(ps => ps.PsId == productSpecId)?.PsProductId;
        //                    if (productId != null)
        //                    {
        //                        if (productCounts.ContainsKey(productId))
        //                        {
        //                            productCounts[productId]++;
        //                        }
        //                        else
        //                        {
        //                            productCounts[productId] = 1;
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //        // 构建返回的饼图数据
        //        foreach (var packageId in packageCounts.Keys)
        //        {
        //            var packageName = package.FirstOrDefault(p => p.PpId == packageId)?.PpName;
        //            cake.Add(new { value = packageCounts[packageId], name = packageName });
        //        }
        //        foreach (var productId in productCounts.Keys)
        //        {
        //            var productName = product.FirstOrDefault(p => p.PId == productId)?.PName;
        //            cake.Add(new { value = productCounts[productId], name = productName });
        //        }

        //        // 客户消费排行
        //        var customs_order_row_query = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1))
        //            .GroupBy(d => d.OCustomerId) // 按客户 ID 分组
        //            .Select(g => new
        //            {
        //                name = g.FirstOrDefault().OCustomerName, // 客户名字
        //                count = g.Count(), // 消费次数
        //                money = g.Sum(d => d.OTotalAmount), // 总消费金额
        //                time = g.Max(d => d.OCreateTime) // 最近消费时间
        //            })
        //            .OrderByDescending(g => g.money) // 按总消费金额降序排序
        //            .Take(5) // 只取前五名客户
        //            .Select(g => new
        //            {
        //                name = g.name,
        //                count = g.count,
        //                money = g.money,
        //                time = g.time.Value.ToString("yyyy-MM-dd hh:mm:ss") // 格式化时间
        //            })
        //            .ToListAsync();

        //        // 将查询结果转换为 List<dynamic>
        //        customs_order_row = customs_order_row_query.Select(item => (dynamic)item).ToList();

        //        //预约时段分布
        //        // 预约时段分布
        //        // 预约时段分布
        //        var timeSlots = new List<string> { "09:00-12:00", "14:00-17:00", "18:00-21:00" };

        //        var groupedData = _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod == now)
        //            .AsEnumerable() // 转换为客户端评估
        //            .Select(d => new
        //            {
        //                TimeSlot = TimeSpan.Parse(d.ATime).Hours >= 9 && TimeSpan.Parse(d.ATime).Hours < 12 ? "09:00-12:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 14 && TimeSpan.Parse(d.ATime).Hours < 17 ? "14:00-17:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 18 && TimeSpan.Parse(d.ATime).Hours < 21 ? "18:00-21:00" : "Other"
        //            })
        //            .Where(d => d.TimeSlot != "Other") // 过滤掉不在指定时间段的预约
        //            .GroupBy(d => d.TimeSlot)
        //            .Select(g => new { TimeSlot = g.Key, Count = g.Count() }) // 按时间段分组并计数
        //            .ToList();

        //        // 确保所有时间段都有计数
        //        appointment_interval_count = timeSlots.Select(slot => groupedData.FirstOrDefault(g => g.TimeSlot == slot)?.Count ?? 0).ToList();

        //    }
        //    else if (section == "近7天")
        //    {
        //        // 近7天的逻辑
        //    }
        //    else if (section == "近30天")
        //    {
        //        // 近30天的逻辑
        //    }

        //    return Get_Result(1, "ok", new
        //    {
        //        module = new
        //        {
        //            appointment_count = appointment_count, // 预约总数
        //            order_money = order_money, // 总营业额
        //            order_count = order_count, // 总订单数
        //            customs = customs, // 总客户量
        //            curve = new
        //            {
        //                xData = xData.ToArray(), // 时间
        //                orderData = orderData.ToArray(), // 每个时间段的订单数量
        //                incomeData = incomeData.ToArray(), // 每个时间段的总金额
        //            }, // 订单与收入数据
        //            cake = cake, // 服务项目占比
        //            customs_order_row = customs_order_row, // 客户消费排行
        //            appointment_interval_count = appointment_interval_count//预约时段分布
        //        },
        //    });
        //}


        //public async Task<Api_Result_Dto> Get_Report(string section)
        //{
        //    var appointment_count = 0;
        //    decimal? order_money = 0;
        //    var order_count = 0;
        //    var customs = 0;
        //    List<string> xData = new List<string>();
        //    List<int> orderData = new List<int>();
        //    List<decimal?> incomeData = new List<decimal?>();
        //    var cake = new List<dynamic>();
        //    var customs_order_row = new List<dynamic>(); // 声明一个容器存储客户消费排行的数据
        //    List<int> appointment_interval_count = new List<int>();

        //    if (section == "当天")
        //    {
        //        var now = DateTime.Now.Date;
        //        // 预约总数
        //        appointment_count = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod == now).CountAsync();
        //        // 总营业额
        //        order_money = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1) && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //        // 总订单数
        //        order_count = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1)).CountAsync();
        //        // 总客户量
        //        var appointment_ids = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod == now).Select(d => d.ACustomerId).ToListAsync();
        //        var order_id = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1)).Select(d => d.OCustomerId).ToListAsync();
        //        customs = appointment_ids.Union(order_id).Count();

        //        // 订单与收入数据
        //        for (int i = 0; i < 12; i++)
        //        {
        //            var start = now.AddHours(i * 2);
        //            var end = start.AddHours(2);

        //            // 时间段描述
        //            string timeDescription;
        //            if (i == 11) // 最后一个时间段
        //            {
        //                timeDescription = "22时-24时";
        //            }
        //            else
        //            {
        //                timeDescription = $"{start.Hour}时-{end.Hour}时";
        //            }
        //            xData.Add(timeDescription);

        //            // 每个时间段的订单数量
        //            var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < end).CountAsync();
        //            orderData.Add(orders);

        //            // 每个时间段的总金额
        //            var totalAmount = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < end && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //            incomeData.Add(totalAmount);
        //        }

        //        // 获取订单详情
        //        var order_ids = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1)).Select(d => d.OId).ToListAsync();
        //        var order_details = await _order_IOC._ordersDetails_EFCore.GetAll(d => order_ids.Contains(d.OdOrderId)).Select(d => new
        //        {
        //            d.OdOrderId,
        //            d.OdPackageId, // 套餐id 逗号隔开
        //            d.OdProductId // 产品规格id 逗号隔开
        //        }).ToListAsync();

        //        // 获取套餐表
        //        var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
        //        {
        //            d.PpId,
        //            d.PpName,
        //        }).ToListAsync();

        //        // 获取产品表
        //        var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
        //        {
        //            d.PId,
        //            d.PName,
        //        }).ToListAsync();

        //        // 获取产品规格表
        //        var product_span = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
        //        {
        //            d.PsProductId, // 对应产品表的产品id
        //            d.PsId // 产品规格id
        //        }).ToListAsync();

        //        // 计算套餐和产品的数量
        //        var packageCounts = new Dictionary<string, int>();
        //        var productCounts = new Dictionary<string, int>();

        //        foreach (var detail in order_details)
        //        {
        //            if (!string.IsNullOrEmpty(detail.OdPackageId))
        //            {
        //                var packageIds = detail.OdPackageId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var packageId in packageIds)
        //                {
        //                    if (packageCounts.ContainsKey(packageId))
        //                    {
        //                        packageCounts[packageId]++;
        //                    }
        //                    else
        //                    {
        //                        packageCounts[packageId] = 1;
        //                    }
        //                }
        //            }

        //            if (!string.IsNullOrEmpty(detail.OdProductId))
        //            {
        //                var productSpecIds = detail.OdProductId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var productSpecId in productSpecIds)
        //                {
        //                    var productId = product_span.FirstOrDefault(ps => ps.PsId == productSpecId)?.PsProductId;
        //                    if (productId != null)
        //                    {
        //                        if (productCounts.ContainsKey(productId))
        //                        {
        //                            productCounts[productId]++;
        //                        }
        //                        else
        //                        {
        //                            productCounts[productId] = 1;
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //        // 构建返回的饼图数据
        //        foreach (var packageId in packageCounts.Keys)
        //        {
        //            var packageName = package.FirstOrDefault(p => p.PpId == packageId)?.PpName;
        //            cake.Add(new { value = packageCounts[packageId], name = packageName });
        //        }
        //        foreach (var productId in productCounts.Keys)
        //        {
        //            var productName = product.FirstOrDefault(p => p.PId == productId)?.PName;
        //            cake.Add(new { value = productCounts[productId], name = productName });
        //        }

        //        // 客户消费排行
        //        var customs_order_row_query = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= now && d.OCreateTime < now.AddDays(1))
        //            .GroupBy(d => d.OCustomerId) // 按客户 ID 分组
        //            .Select(g => new
        //            {
        //                name = g.FirstOrDefault().OCustomerName, // 客户名字
        //                count = g.Count(), // 消费次数
        //                money = g.Sum(d => d.OTotalAmount), // 总消费金额
        //                time = g.Max(d => d.OCreateTime) // 最近消费时间
        //            })
        //            .OrderByDescending(g => g.money) // 按总消费金额降序排序
        //            .Take(5) // 只取前五名客户
        //            .Select(g => new
        //            {
        //                name = g.name,
        //                count = g.count,
        //                money = g.money,
        //                time = g.time.Value.ToString("yyyy-MM-dd hh:mm:ss") // 格式化时间
        //            })
        //            .ToListAsync();

        //        // 将查询结果转换为 List<dynamic>
        //        customs_order_row = customs_order_row_query.Select(item => (dynamic)item).ToList();

        //        // 预约时段分布
        //        var timeSlots = new List<string> { "09:00-12:00", "14:00-17:00", "18:00-21:00" };

        //        var groupedData = _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod == now)
        //            .AsEnumerable() // 转换为客户端评估
        //            .Select(d => new
        //            {
        //                TimeSlot = TimeSpan.Parse(d.ATime).Hours >= 9 && TimeSpan.Parse(d.ATime).Hours < 12 ? "09:00-12:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 14 && TimeSpan.Parse(d.ATime).Hours < 17 ? "14:00-17:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 18 && TimeSpan.Parse(d.ATime).Hours < 21 ? "18:00-21:00" : "Other"
        //            })
        //            .Where(d => d.TimeSlot != "Other") // 过滤掉不在指定时间段的预约
        //            .GroupBy(d => d.TimeSlot)
        //            .Select(g => new { TimeSlot = g.Key, Count = g.Count() }) // 按时间段分组并计数
        //            .ToList();

        //        // 确保所有时间段都有计数
        //        appointment_interval_count = timeSlots.Select(slot => groupedData.FirstOrDefault(g => g.TimeSlot == slot)?.Count ?? 0).ToList();
        //    }
        //    else if (section == "近7天")
        //    {
        //        var now = DateTime.Now.Date;
        //        var start = now.AddDays(-6); // 7天前的日期

        //        // 预约总数
        //        appointment_count = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now).CountAsync();
        //        // 总营业额
        //        order_money = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1) && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //        // 总订单数
        //        order_count = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1)).CountAsync();
        //        // 总客户量
        //        var appointment_ids = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now).Select(d => d.ACustomerId).ToListAsync();
        //        var order_id = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1)).Select(d => d.OCustomerId).ToListAsync();
        //        customs = appointment_ids.Union(order_id).Count();
        //        // 订单与收入数据（按天统计）
        //        for (int i = 0; i < 7; i++)
        //        {
        //            var date = start.AddDays(i);
        //            xData.Add(date.ToString("yyyy-MM-dd"));

        //            // 每天的订单数量
        //            var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= date && d.OCreateTime < date.AddDays(1)).CountAsync();
        //            orderData.Add(orders);

        //            // 每天的总金额
        //            var totalAmount = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= date && d.OCreateTime < date.AddDays(1) && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //            incomeData.Add(totalAmount);
        //        }

        //        // 获取订单详情
        //        var order_ids = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1)).Select(d => d.OId).ToListAsync();
        //        var order_details = await _order_IOC._ordersDetails_EFCore.GetAll(d => order_ids.Contains(d.OdOrderId)).Select(d => new
        //        {
        //            d.OdOrderId,
        //            d.OdPackageId, // 套餐id 逗号隔开
        //            d.OdProductId // 产品规格id 逗号隔开
        //        }).ToListAsync();

        //        // 获取套餐表
        //        var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
        //        {
        //            d.PpId,
        //            d.PpName,
        //        }).ToListAsync();

        //        // 获取产品表
        //        var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
        //        {
        //            d.PId,
        //            d.PName,
        //        }).ToListAsync();

        //        // 获取产品规格表
        //        var product_span = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
        //        {
        //            d.PsProductId, // 对应产品表的产品id
        //            d.PsId // 产品规格id
        //        }).ToListAsync();

        //        // 计算套餐和产品的数量
        //        var packageCounts = new Dictionary<string, int>();
        //        var productCounts = new Dictionary<string, int>();

        //        foreach (var detail in order_details)
        //        {
        //            if (!string.IsNullOrEmpty(detail.OdPackageId))
        //            {
        //                var packageIds = detail.OdPackageId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var packageId in packageIds)
        //                {
        //                    if (packageCounts.ContainsKey(packageId))
        //                    {
        //                        packageCounts[packageId]++;
        //                    }
        //                    else
        //                    {
        //                        packageCounts[packageId] = 1;
        //                    }
        //                }
        //            }

        //            if (!string.IsNullOrEmpty(detail.OdProductId))
        //            {
        //                var productSpecIds = detail.OdProductId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var productSpecId in productSpecIds)
        //                {
        //                    var productId = product_span.FirstOrDefault(ps => ps.PsId == productSpecId)?.PsProductId;
        //                    if (productId != null)
        //                    {
        //                        if (productCounts.ContainsKey(productId))
        //                        {
        //                            productCounts[productId]++;
        //                        }
        //                        else
        //                        {
        //                            productCounts[productId] = 1;
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //        // 构建返回的饼图数据
        //        foreach (var packageId in packageCounts.Keys)
        //        {
        //            var packageName = package.FirstOrDefault(p => p.PpId == packageId)?.PpName;
        //            cake.Add(new { value = packageCounts[packageId], name = packageName });
        //        }
        //        foreach (var productId in productCounts.Keys)
        //        {
        //            var productName = product.FirstOrDefault(p => p.PId == productId)?.PName;
        //            cake.Add(new { value = productCounts[productId], name = productName });
        //        }

        //        // 客户消费排行
        //        var customs_order_row_query = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1))
        //            .GroupBy(d => d.OCustomerId) // 按客户 ID 分组
        //            .Select(g => new
        //            {
        //                name = g.FirstOrDefault().OCustomerName, // 客户名字
        //                count = g.Count(), // 消费次数
        //                money = g.Sum(d => d.OTotalAmount), // 总消费金额
        //                time = g.Max(d => d.OCreateTime) // 最近消费时间
        //            })
        //            .OrderByDescending(g => g.money) // 按总消费金额降序排序
        //            .Take(5) // 只取前五名客户
        //            .Select(g => new
        //            {
        //                name = g.name,
        //                count = g.count,
        //                money = g.money,
        //                time = g.time.Value.ToString("yyyy-MM-dd hh:mm:ss") // 格式化时间
        //            })
        //            .ToListAsync();

        //        // 将查询结果转换为 List<dynamic>
        //        customs_order_row = customs_order_row_query.Select(item => (dynamic)item).ToList();

        //        // 预约时段分布
        //        var timeSlots = new List<string> { "09:00-12:00", "14:00-17:00", "18:00-21:00" };

        //        var groupedData = _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now)
        //            .AsEnumerable() // 转换为客户端评估
        //            .Select(d => new
        //            {
        //                TimeSlot = TimeSpan.Parse(d.ATime).Hours >= 9 && TimeSpan.Parse(d.ATime).Hours < 12 ? "09:00-12:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 14 && TimeSpan.Parse(d.ATime).Hours < 17 ? "14:00-17:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 18 && TimeSpan.Parse(d.ATime).Hours < 21 ? "18:00-21:00" : "Other"
        //            })
        //            .Where(d => d.TimeSlot != "Other") // 过滤掉不在指定时间段的预约
        //            .GroupBy(d => d.TimeSlot)
        //            .Select(g => new { TimeSlot = g.Key, Count = g.Count() }) // 按时间段分组并计数
        //            .ToList();

        //        // 确保所有时间段都有计数
        //        appointment_interval_count = timeSlots.Select(slot => groupedData.FirstOrDefault(g => g.TimeSlot == slot)?.Count ?? 0).ToList();
        //    }
        //    else if (section == "近30天")
        //    {
        //        var now = DateTime.Now.Date;
        //        var start = now.AddDays(-30); // 30天前的日期

        //        // 预约总数
        //        appointment_count = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now).CountAsync();
        //        // 总营业额
        //        order_money = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1) && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //        // 总订单数
        //        order_count = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1)).CountAsync();
        //        // 总客户量
        //        var appointment_ids = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now).Select(d => d.ACustomerId).ToListAsync();
        //        var order_id = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1)).Select(d => d.OCustomerId).ToListAsync();
        //        customs = appointment_ids.Union(order_id).Count();

        //        // 订单与收入数据（按5天统计）
        //        for (int i = 0; i < 6; i++) // 30天分为6个5天区间
        //        {
        //            var intervalStart = start.AddDays(i * 5);
        //            var intervalEnd = intervalStart.AddDays(5);

        //            xData.Add($"{intervalStart.ToString("yyyy-MM-dd")} - {intervalEnd.ToString("yyyy-MM-dd")}");

        //            // 每个5天区间的订单数量
        //            var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= intervalStart && d.OCreateTime < intervalEnd).CountAsync();
        //            orderData.Add(orders);
        //            // 每个5天区间的总金额
        //            var totalAmount = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= intervalStart && d.OCreateTime < intervalEnd && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
        //            incomeData.Add(totalAmount);
        //        }

        //        // 获取订单详情
        //        var order_ids = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1)).Select(d => d.OId).ToListAsync();
        //        var order_details = await _order_IOC._ordersDetails_EFCore.GetAll(d => order_ids.Contains(d.OdOrderId)).Select(d => new
        //        {
        //            d.OdOrderId,
        //            d.OdPackageId, // 套餐id 逗号隔开
        //            d.OdProductId // 产品规格id 逗号隔开
        //        }).ToListAsync();

        //        // 获取套餐表
        //        var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
        //        {
        //            d.PpId,
        //            d.PpName,
        //        }).ToListAsync();

        //        // 获取产品表
        //        var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
        //        {
        //            d.PId,
        //            d.PName,
        //        }).ToListAsync();

        //        // 获取产品规格表
        //        var product_span = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
        //        {
        //            d.PsProductId, // 对应产品表的产品id
        //            d.PsId // 产品规格id
        //        }).ToListAsync();

        //        // 计算套餐和产品的数量
        //        var packageCounts = new Dictionary<string, int>();
        //        var productCounts = new Dictionary<string, int>();

        //        foreach (var detail in order_details)
        //        {
        //            if (!string.IsNullOrEmpty(detail.OdPackageId))
        //            {
        //                var packageIds = detail.OdPackageId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var packageId in packageIds)
        //                {
        //                    if (packageCounts.ContainsKey(packageId))
        //                    {
        //                        packageCounts[packageId]++;
        //                    }
        //                    else
        //                    {
        //                        packageCounts[packageId] = 1;
        //                    }
        //                }
        //            }

        //            if (!string.IsNullOrEmpty(detail.OdProductId))
        //            {
        //                var productSpecIds = detail.OdProductId.Split(',').Select(id => id.Trim()).ToList();
        //                foreach (var productSpecId in productSpecIds)
        //                {
        //                    var productId = product_span.FirstOrDefault(ps => ps.PsId == productSpecId)?.PsProductId;
        //                    if (productId != null)
        //                    {
        //                        if (productCounts.ContainsKey(productId))
        //                        {
        //                            productCounts[productId]++;
        //                        }
        //                        else
        //                        {
        //                            productCounts[productId] = 1;
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //        // 构建返回的饼图数据
        //        foreach (var packageId in packageCounts.Keys)
        //        {
        //            var packageName = package.FirstOrDefault(p => p.PpId == packageId)?.PpName;
        //            cake.Add(new { value = packageCounts[packageId], name = packageName });
        //        }
        //        foreach (var productId in productCounts.Keys)
        //        {
        //            var productName = product.FirstOrDefault(p => p.PId == productId)?.PName;
        //            cake.Add(new { value = productCounts[productId], name = productName });
        //        }

        //        // 客户消费排行
        //        var customs_order_row_query = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1))
        //            .GroupBy(d => d.OCustomerId) // 按客户 ID 分组
        //            .Select(g => new
        //            {
        //                name = g.FirstOrDefault().OCustomerName, // 客户名字
        //                count = g.Count(), // 消费次数
        //                money = g.Sum(d => d.OTotalAmount), // 总消费金额
        //                time = g.Max(d => d.OCreateTime) // 最近消费时间
        //            })
        //            .OrderByDescending(g => g.money) // 按总消费金额降序排序
        //            .Take(5) // 只取前五名客户
        //            .Select(g => new
        //            {
        //                name = g.name,
        //                count = g.count,
        //                money = g.money,
        //                time = g.time.Value.ToString("yyyy-MM-dd hh:mm:ss") // 格式化时间
        //            })
        //            .ToListAsync();

        //        // 将查询结果转换为 List<dynamic>
        //        customs_order_row = customs_order_row_query.Select(item => (dynamic)item).ToList();

        //        // 预约时段分布
        //        var timeSlots = new List<string> { "09:00-12:00", "14:00-17:00", "18:00-21:00" };

        //        var groupedData = _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now)
        //            .AsEnumerable() // 转换为客户端评估
        //            .Select(d => new
        //            {
        //                TimeSlot = TimeSpan.Parse(d.ATime).Hours >= 9 && TimeSpan.Parse(d.ATime).Hours < 12 ? "09:00-12:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 14 && TimeSpan.Parse(d.ATime).Hours < 17 ? "14:00-17:00" :
        //                           TimeSpan.Parse(d.ATime).Hours >= 18 && TimeSpan.Parse(d.ATime).Hours < 21 ? "18:00-21:00" : "Other"
        //            })
        //            .Where(d => d.TimeSlot != "Other") // 过滤掉不在指定时间段的预约
        //            .GroupBy(d => d.TimeSlot)
        //            .Select(g => new { TimeSlot = g.Key, Count = g.Count() }) // 按时间段分组并计数
        //            .ToList();

        //        // 确保所有时间段都有计数
        //        appointment_interval_count = timeSlots.Select(slot => groupedData.FirstOrDefault(g => g.TimeSlot == slot)?.Count ?? 0).ToList();
        //    }

        //    return Get_Result(1, "ok", new
        //    {
        //        module = new
        //        {
        //            appointment_count = appointment_count, // 预约总数
        //            order_money = order_money, // 总营业额
        //            order_count = order_count, // 总订单数
        //            customs = customs, // 总客户量
        //            curve = new
        //            {
        //                xData = xData.ToArray(), // 时间
        //                orderData = orderData.ToArray(), // 每个时间段的订单数量
        //                incomeData = incomeData.ToArray(), // 每个时间段的总金额
        //            }, // 订单与收入数据
        //            cake = cake, // 服务项目占比
        //            customs_order_row = customs_order_row, // 客户消费排行
        //            appointment_interval_count = appointment_interval_count // 预约时段分布
        //        },
        //    });
        //}


        public async Task<Api_Result_Dto> Get_Report(string section)
        {
            var now = DateTime.Now.Date;

            // 根据时间范围初始化变量
            DateTime start;
            int intervalCount;
            string[] timeSlots = { "09:00-12:00", "14:00-17:00", "18:00-21:00" };

            switch (section)
            {
                case "当天":
                    start = now;
                    intervalCount = 12; // 每2小时一个区间
                    break;
                case "近7天":
                    start = now.AddDays(-6);
                    intervalCount = 7; // 每天一个区间
                    break;
                case "近30天":
                    start = now.AddDays(-30);
                    intervalCount = 6; // 每5天一个区间
                    break;
                default:
                    throw new ArgumentException("Invalid section");
            }

            // 查询预约总数
            var appointment_count = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now).CountAsync();

            // 查询总营业额和总订单数
            var orderQuery = _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1));
            var order_money = await orderQuery.Where(d => d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
            var order_count = await orderQuery.CountAsync();

            // 查询总客户量
            var appointment_ids = await _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now).Select(d => d.ACustomerId).ToListAsync();
            var order_id = await orderQuery.Select(d => d.OCustomerId).ToListAsync();
            var customs = appointment_ids.Union(order_id).Count();

            // 查询订单与收入数据
            List<string> xData = new List<string>();
            List<int> orderData = new List<int>();
            List<decimal?> incomeData = new List<decimal?>();

            if (section == "当天")
            {
                for (int i = 0; i < intervalCount; i++)
                {
                    var startHour = now.AddHours(i * 2);
                    var endHour = startHour.AddHours(2);

                    string timeDescription = i == 11 ? "22时-24时" : $"{startHour.Hour}时-{endHour.Hour}时";
                    xData.Add(timeDescription);

                    var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= startHour && d.OCreateTime < endHour).CountAsync();
                    orderData.Add(orders);

                    var totalAmount = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= startHour && d.OCreateTime < endHour && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
                    incomeData.Add(totalAmount);
                }
            }
            else if (section == "近7天")
            {
                for (int i = 0; i < intervalCount; i++)
                {
                    var date = start.AddDays(i);
                    xData.Add(date.ToString("yyyy-MM-dd"));

                    var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= date && d.OCreateTime < date.AddDays(1)).CountAsync();
                    orderData.Add(orders);

                    var totalAmount = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= date && d.OCreateTime < date.AddDays(1) && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
                    incomeData.Add(totalAmount);
                }
            }
            else if (section == "近30天")
            {
                for (int i = 0; i < intervalCount; i++)
                {
                    var intervalStart = start.AddDays(i * 5);
                    var intervalEnd = intervalStart.AddDays(5);

                    xData.Add($"{intervalStart.ToString("yyyy-MM-dd")} - {intervalEnd.ToString("yyyy-MM-dd")}");

                    var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= intervalStart && d.OCreateTime < intervalEnd).CountAsync();
                    orderData.Add(orders);

                    var totalAmount = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= intervalStart && d.OCreateTime < intervalEnd && d.OPayStatus == 1).Select(d => d.OTotalAmount).SumAsync();
                    incomeData.Add(totalAmount);
                }
            }

            // 查询订单详情
            var order_ids = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1)).Select(d => d.OId).ToListAsync();
            var order_details = await _order_IOC._ordersDetails_EFCore.GetAll(d => order_ids.Contains(d.OdOrderId)).Select(d => new
            {
                d.OdOrderId,
                d.OdPackageId, // 套餐id 逗号隔开
                d.OdProductId // 产品规格id 逗号隔开
            }).ToListAsync();

            // 查询套餐表、产品表和产品规格表
            var package = await _product_IOC._productPackage_EFCore.GetAll().Select(d => new
            {
                d.PpId,
                d.PpName,
            }).ToListAsync();

            var product = await _product_IOC._product_EFCore.GetAll().Select(d => new
            {
                d.PId,
                d.PName,
            }).ToListAsync();

            var product_span = await _product_IOC._productSpecs_EFCore.GetAll().Select(d => new
            {
                d.PsProductId, // 对应产品表的产品id
                d.PsId // 产品规格id
            }).ToListAsync();

            // 计算套餐和产品的数量
            var packageCounts = new Dictionary<string, int>();
            var productCounts = new Dictionary<string, int>();

            foreach (var detail in order_details)
            {
                if (!string.IsNullOrEmpty(detail.OdPackageId))
                {
                    var packageIds = detail.OdPackageId.Split(',').Select(id => id.Trim()).ToList();
                    foreach (var packageId in packageIds)
                    {
                        if (packageCounts.ContainsKey(packageId))
                        {
                            packageCounts[packageId]++;
                        }
                        else
                        {
                            packageCounts[packageId] = 1;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(detail.OdProductId))
                {
                    var productSpecIds = detail.OdProductId.Split(',').Select(id => id.Trim()).ToList();
                    foreach (var productSpecId in productSpecIds)
                    {
                        var productId = product_span.FirstOrDefault(ps => ps.PsId == productSpecId)?.PsProductId;
                        if (productId != null)
                        {
                            if (productCounts.ContainsKey(productId))
                            {
                                productCounts[productId]++;
                            }
                            else
                            {
                                productCounts[productId] = 1;
                            }
                        }
                    }
                }
            }

            // 构建返回的饼图数据
            var cake = new List<dynamic>();
            foreach (var packageId in packageCounts.Keys)
            {
                var packageName = package.FirstOrDefault(p => p.PpId == packageId)?.PpName;
                cake.Add(new { value = packageCounts[packageId], name = packageName });
            }
            foreach (var productId in productCounts.Keys)
            {
                var productName = product.FirstOrDefault(p => p.PId == productId)?.PName;
                cake.Add(new { value = productCounts[productId], name = productName });
            }

            // 客户消费排行
            var customs_order_row = await _order_IOC._orders_EFCore.GetAll(d => d.OCreateTime >= start && d.OCreateTime < now.AddDays(1))
                .GroupBy(d => d.OCustomerId) // 按客户 ID 分组
                .Select(g => new
                {
                    name = g.FirstOrDefault().OCustomerName, // 客户名字
                    count = g.Count(), // 消费次数
                    money = g.Sum(d => d.OTotalAmount), // 总消费金额
                    time = g.Max(d => d.OCreateTime) // 最近消费时间
                })
                .OrderByDescending(g => g.money) // 按总消费金额降序排序
                .Take(5) // 只取前五名客户
                .Select(g => new
                {
                    name = g.name,
                    count = g.count,
                    money = g.money,
                    time = g.time.Value.ToString("yyyy-MM-dd hh:mm:ss") // 格式化时间
                })
                .ToListAsync();

            // 预约时段分布
            var groupedData = _appointment_IOC._appointment_EFCore.GetAll(d => d.APeriod >= start && d.APeriod <= now)
                .AsEnumerable() // 转换为客户端评估
                .Select(d => new
                {
                    TimeSlot = TimeSpan.Parse(d.ATime).Hours >= 9 && TimeSpan.Parse(d.ATime).Hours < 12 ? "09:00-12:00" :
                      TimeSpan.Parse(d.ATime).Hours >= 14 && TimeSpan.Parse(d.ATime).Hours < 17 ? "14:00-17:00" :
                    TimeSpan.Parse(d.ATime).Hours >= 18 && TimeSpan.Parse(d.ATime).Hours < 21 ? "18:00-21:00" : "Other"
                })
                .Where(d => d.TimeSlot != "Other") // 过滤掉不在指定时间段的预约
                .GroupBy(d => d.TimeSlot)
                .Select(g => new { TimeSlot = g.Key, Count = g.Count() }) // 按时间段分组并计数
                .ToList();
            // 确保所有时间段都有计数
            var appointment_interval_count = timeSlots.Select(slot => groupedData.FirstOrDefault(g => g.TimeSlot == slot)?.Count ?? 0).ToList();

            // 返回结果
            return Get_Result(1, "ok", new
            {
                appointment_count = appointment_count, // 预约总数
                order_money = order_money, // 总营业额
                order_count = order_count, // 总订单数
                customs = customs, // 总客户量
                curve = new
                {
                    xData = xData.ToArray(), // 时间
                    orderData = orderData.ToArray(), // 每个时间段的订单数量
                    incomeData = incomeData.ToArray(), // 每个时间段的总金额
                }, // 订单与收入数据
                cake = cake, // 服务项目占比
                customs_order_row = customs_order_row, // 客户消费排行
                appointment_interval_count = appointment_interval_count // 预约时段分布
            });
            
        }

        /// <summary>
        /// 获取每个房间的待支付订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Room_Order(Orders_Dto dto)
        {
            // 获取订单数据
            var orders = await _order_IOC._orders_EFCore.GetAll(out int total, dto.page, dto.limit, false,
                d => d.OCreateTime, d => d.OPayStatus == 0 && d.ORoomId == dto.r_id)
                .Select(d => new
                {
                    d.OId,
                    d.OCustomerName,
                    d.OCustomerPhone,
                    d.OTotalAmount,
                    d.ORoomId,
                }).ToListAsync();

            // 获取订单详情
            var orderDetails = await _order_IOC._ordersDetails_EFCore.GetAll(d => orders.Select(o => o.OId).Contains(d.OdOrderId))
                .Select(d => new
                {
                    d.OdOrderId,
                    d.OdPackageId,
                    d.OdProductId,
                }).ToListAsync();

            // 根据房间 ID 分组并处理数据
            var groupedOrders = orders.GroupBy(o => o.ORoomId)
                .Select(group => new
                {
                    id = group.First().OId, // 房间 ID
                    name = group.First().OCustomerName,
                    phone = group.First().OCustomerPhone,
                    money = group.Sum(o => o.OTotalAmount),
                    count = orderDetails.Where(od => group.Select(o => o.OId).Contains(od.OdOrderId))
                        .Select(od => new
                        {
                            // 计算每个订单详情的项目数量
                            ItemCount = ((od.OdPackageId != null && od.OdPackageId != "") ? 1 : 0 )+
                                        ((od.OdProductId != null && od.OdProductId != "") ? 1 : 0)
                        })
                        .Sum(od => od.ItemCount)
                }).ToList();

            // 返回结果
            return Get_Result(1, "ok", new
            {
                total = total,
                data = groupedOrders,
            });
        }
    }
}
